package com.kzj.common.exceptionHandler;

import com.kzj.common.constant.GlobalConstant;
import com.kzj.common.exception.MyException;
import com.kzj.common.result.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

@ControllerAdvice(annotations = {RestController.class, Controller.class})
@ResponseBody
@Slf4j
public class GlobalExceptionHandler {
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Result methodArgumentNotValidException(MethodArgumentNotValidException exception)
    {
        StringBuilder errorMsg= new StringBuilder("");
        for (ObjectError error : exception.getAllErrors()) {
            errorMsg.append(error.getDefaultMessage()+"\n");
        }
        log.warn(errorMsg.toString());
        return Result.error(errorMsg.toString());
    }
    @ExceptionHandler(MyException.class)
    public Result myExceptionHandler(MyException exception){
        log.warn(exception.getMessage());
        return Result.error(exception.getMessage());
    }
    @ExceptionHandler(Exception.class)
    public Result exceptionHandler(Exception exception)
    {
        exception.printStackTrace();
        return Result.error(GlobalConstant.SYSTEM_ERROR);
    }
}
